package swingxrcp.framework.util;

import java.util.Iterator;
import java.util.StringTokenizer;

public class StringUtils {

	public static String toString(Object obj) {
        if (obj == null) {
			return "";
		} else {
			String refobj = obj.toString();
			return refobj.trim();
		}
	}

    public static String[] parse(String str) {
        return str.split("\\,");
    }

    public static String[] parse(String str, String regEx) {
        return str.split("\\" + regEx);
    }

    /**
     * 字符串转型成boolean
     *
     * @param str
     * @return
     */
    public static boolean getBoolean(String str) {
        if ("true".equals(str)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 第一个字母小写
     *
     * @param str
     * @return
     */
    public static String firstWordToLowerCase(String str) {
        return str.substring(0, 1).toLowerCase()
                + str.substring(1, str.length());
    }

    public static String clean(String str) {
        return str != null ? str.trim() : "";
    }

    public static String trim(String str) {
        return str != null ? str.trim() : null;
    }

    public static String deleteWhitespace(String str) {
        StringBuffer buffer = new StringBuffer();
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                buffer.append(str.charAt(i));
            }
        }

        return buffer.toString();
    }

    public static boolean isNotEmpty(String str) {
        return str != null && str.length() > 0;
    }

    public static boolean isEmpty(String str) {
        return str == null || str.trim().length() == 0;
    }

    public static boolean equals(String str1, String str2) {
        return str1 != null ? str1.equals(str2) : str2 == null;
    }

    public static boolean equalsIgnoreCase(String str1, String str2) {
        return str1 != null ? str1.equalsIgnoreCase(str2) : str2 == null;
    }

    public static int indexOfAny(String str, String searchStrs[]) {
        if (str == null || searchStrs == null) {
            return -1;
        }
        int sz = searchStrs.length;
        int ret = 0x7fffffff;
        int tmp = 0;
        for (int i = 0; i < sz; i++) {
            tmp = str.indexOf(searchStrs[i]);
            if (tmp != -1 && tmp < ret) {
                ret = tmp;
            }
        }

        return ret != 0x7fffffff ? ret : -1;
    }

    public static int lastIndexOfAny(String str, String searchStrs[]) {
        if (str == null || searchStrs == null) {
            return -1;
        }
        int sz = searchStrs.length;
        int ret = -1;
        int tmp = 0;
        for (int i = 0; i < sz; i++) {
            tmp = str.lastIndexOf(searchStrs[i]);
            if (tmp > ret) {
                ret = tmp;
            }
        }

        return ret;
    }

    public static String substring(String str, int start) {
        if (str == null) {
            return null;
        }
        if (start < 0) {
            start = str.length() + start;
        }
        if (start < 0) {
            start = 0;
        }
        if (start > str.length()) {
            return "";
        } else {
            return str.substring(start);
        }
    }

    public static String substring(String str, int start, int end) {
        if (str == null) {
            return null;
        }
        if (end < 0) {
            end = str.length() + end;
        }
        if (start < 0) {
            start = str.length() + start;
        }
        if (end > str.length()) {
            end = str.length();
        }
        if (start > end) {
            return "";
        }
        if (start < 0) {
            start = 0;
        }
        if (end < 0) {
            end = 0;
        }
        return str.substring(start, end);
    }

    public static String left(String str, int len) {
        if (len < 0) {
            throw new IllegalArgumentException("Requested String length " + len
                    + " is less than zero");
        }
        if (str == null || str.length() <= len) {
            return str;
        } else {
            return str.substring(0, len);
        }
    }

    public static String right(String str, int len) {
        if (len < 0) {
            throw new IllegalArgumentException("Requested String length " + len
                    + " is less than zero");
        }
        if (str == null || str.length() <= len) {
            return str;
        } else {
            return str.substring(str.length() - len);
        }
    }

    public static String mid(String str, int pos, int len) {
        if (pos < 0 || str != null && pos > str.length()) {
            throw new StringIndexOutOfBoundsException("String index " + pos
                    + " is out of bounds");
        }
        if (len < 0) {
            throw new IllegalArgumentException("Requested String length " + len
                    + " is less than zero");
        }
        if (str == null) {
            return null;
        }
        if (str.length() <= pos + len) {
            return str.substring(pos);
        } else {
            return str.substring(pos, pos + len);
        }
    }

    public static String[] split(String str) {
        return split(str, null, -1);
    }

    public static String[] split(String text, String separator) {
        return split(text, separator, -1);
    }

    public static String[] split(String str, String separator, int max) {
        StringTokenizer tok = null;
        if (separator == null) {
            tok = new StringTokenizer(str);
        } else {
            tok = new StringTokenizer(str, separator);
        }
        int listSize = tok.countTokens();
        if (max > 0 && listSize > max) {
            listSize = max;
        }
        String list[] = new String[listSize];
        int i = 0;
        int lastTokenBegin = 0;
        int lastTokenEnd = 0;
        while (tok.hasMoreTokens()) {
            if (max > 0 && i == listSize - 1) {
                String endToken = tok.nextToken();
                lastTokenBegin = str.indexOf(endToken, lastTokenEnd);
                list[i] = str.substring(lastTokenBegin);
                break;
            }
            list[i] = tok.nextToken();
            lastTokenBegin = str.indexOf(list[i], lastTokenEnd);
            lastTokenEnd = lastTokenBegin + list[i].length();
            i++;
        }
        return list;
    }

    public static String concatenate(Object array[]) {
        return join(array, "");
    }

    public static String join(Object array[], String separator) {
        if (separator == null) {
            separator = "";
        }
        int arraySize = array.length;
        int bufSize = arraySize != 0 ? (array[0].toString().length() + separator
                .length())
                * arraySize
                : 0;
        StringBuffer buf = new StringBuffer(bufSize);
        for (int i = 0; i < arraySize; i++) {
            if (i > 0) {
                buf.append(separator);
            }
            buf.append(array[i]);
        }

        return buf.toString();
    }

    public static String join(Iterator iterator, String separator) {
        if (separator == null) {
            separator = "";
        }
        StringBuffer buf = new StringBuffer(256);
        while (iterator.hasNext()) {
            buf.append(iterator.next());
            if (iterator.hasNext()) {
                buf.append(separator);
            }
        }
        return buf.toString();
    }

    public static String replaceOnce(String text, String repl, String with) {
        return replace(text, repl, with, 1);
    }

    public static String replace(String text, String repl, String with) {
        return replace(text, repl, with, -1);
    }

    public static String replace(String text, String repl, String with, int max) {
        if (text == null) {
            return null;
        }
        StringBuffer buf = new StringBuffer(text.length());
        int start = 0;
        for (int end = 0; (end = text.indexOf(repl, start)) != -1;) {
            buf.append(text.substring(start, end)).append(with);
            start = end + repl.length();
            if (--max == 0) {
                break;
            }
        }

        buf.append(text.substring(start));
        return buf.toString();
    }

    public static String overlayString(String text, String overlay, int start,
            int end) {
        return (new StringBuffer(
                ((start + overlay.length() + text.length()) - end) + 1))
                .append(text.substring(0, start)).append(overlay).append(
                        text.substring(end)).toString();
    }

    public static String center(String str, int size) {
        return center(str, size, " ");
    }

    public static String center(String str, int size, String delim) {
        int sz = str.length();
        int p = size - sz;
        if (p < 1) {
            return str;
        } else {
            str = leftPad(str, sz + p / 2, delim);
            str = rightPad(str, size, delim);
            return str;
        }
    }

    public static String chomp(String str) {
        return chomp(str, "\n");
    }

    public static String chomp(String str, String sep) {
        int idx = str.lastIndexOf(sep);
        if (idx != -1) {
            return str.substring(0, idx);
        } else {
            return str;
        }
    }

    public static String chompLast(String str) {
        return chompLast(str, "\n");
    }

    public static String chompLast(String str, String sep) {
        if (str.length() == 0) {
            return str;
        }
        String sub = str.substring(str.length() - sep.length());
        if (sep.equals(sub)) {
            return str.substring(0, str.length() - sep.length());
        } else {
            return str;
        }
    }

    public static String getChomp(String str, String sep) {
        int idx = str.lastIndexOf(sep);
        if (idx == str.length() - sep.length()) {
            return sep;
        }
        if (idx != -1) {
            return str.substring(idx);
        } else {
            return "";
        }
    }

    public static String prechomp(String str, String sep) {
        int idx = str.indexOf(sep);
        if (idx != -1) {
            return str.substring(idx + sep.length());
        } else {
            return str;
        }
    }

    public static String getPrechomp(String str, String sep) {
        int idx = str.indexOf(sep);
        if (idx != -1) {
            return str.substring(0, idx + sep.length());
        } else {
            return "";
        }
    }

    public static String chop(String str) {
        if ("".equals(str)) {
            return "";
        }
        if (str.length() == 1) {
            return "";
        }
        int lastIdx = str.length() - 1;
        String ret = str.substring(0, lastIdx);
        char last = str.charAt(lastIdx);
        if (last == '\n' && ret.charAt(lastIdx - 1) == '\r') {
            return ret.substring(0, lastIdx - 1);
        } else {
            return ret;
        }
    }

    public static String chopNewline(String str) {
        int lastIdx = str.length() - 1;
        char last = str.charAt(lastIdx);
        if (last == '\n') {
            if (str.charAt(lastIdx - 1) == '\r') {
                lastIdx--;
            }
        } else {
            lastIdx++;
        }
        return str.substring(0, lastIdx);
    }

    public static String escape(String str) {
        int sz = str.length();
        StringBuffer buffer = new StringBuffer(2 * sz);
        for (int i = 0; i < sz; i++) {
            char ch = str.charAt(i);
            if (ch > '\u0FFF') {
                buffer.append("\\u" + Integer.toHexString(ch));
            } else if (ch > '\377') {
                buffer.append("\\u0" + Integer.toHexString(ch));
            } else if (ch > '\177') {
                buffer.append("\\u00" + Integer.toHexString(ch));
            } else if (ch < ' ') {
                switch (ch) {
                    case 8: // '\b'
                        buffer.append('\\');
                        buffer.append('b');
                        break;

                    case 10: // '\n'
                        buffer.append('\\');
                        buffer.append('n');
                        break;

                    case 9: // '\t'
                        buffer.append('\\');
                        buffer.append('t');
                        break;

                    case 12: // '\f'
                        buffer.append('\\');
                        buffer.append('f');
                        break;

                    case 13: // '\r'
                        buffer.append('\\');
                        buffer.append('r');
                        break;

                    case 11: // '\013'
                    default:
                        if (ch > '\017') {
                            buffer.append("\\u00" + Integer.toHexString(ch));
                        } else {
                            buffer.append("\\u000" + Integer.toHexString(ch));
                        }
                        break;
                }
            } else {
                switch (ch) {
                    case 39: // '\''
                        buffer.append('\\');
                        buffer.append('\'');
                        break;

                    case 34: // '"'
                        buffer.append('\\');
                        buffer.append('"');
                        break;

                    case 92: // '\\'
                        buffer.append('\\');
                        buffer.append('\\');
                        break;

                    default:
                        buffer.append(ch);
                        break;
                }
            }
        }

        return buffer.toString();
    }

    public static String repeat(String str, int repeat) {
        StringBuffer buffer = new StringBuffer(repeat * str.length());
        for (int i = 0; i < repeat; i++) {
            buffer.append(str);
        }

        return buffer.toString();
    }

    public static String rightPad(String str, int size) {
        return rightPad(str, size, " ");
    }

    public static String rightPad(String str, int size, String delim) {
        size = (size - str.length()) / delim.length();
        if (size > 0) {
            str = str + repeat(delim, size);
        }
        return str;
    }

    public static String leftPad(String str, int size) {
        return leftPad(str, size, " ");
    }

    public static String leftPad(String str, int size, String delim) {
        size = (size - str.length()) / delim.length();
        if (size > 0) {
            str = repeat(delim, size) + str;
        }
        return str;
    }

    public static String strip(String str) {
        return strip(str, null);
    }

    public static String strip(String str, String delim) {
        str = stripStart(str, delim);
        return stripEnd(str, delim);
    }

    public static String[] stripAll(String strs[]) {
        return stripAll(strs, null);
    }

    public static String[] stripAll(String strs[], String delimiter) {
        if (strs == null || strs.length == 0) {
            return strs;
        }
        int sz = strs.length;
        String newArr[] = new String[sz];
        for (int i = 0; i < sz; i++) {
            newArr[i] = strip(strs[i], delimiter);
        }

        return newArr;
    }

    public static String stripEnd(String str, String strip) {
        if (str == null) {
            return null;
        }
        int end = str.length();
        if (strip == null) {
            for (; end != 0 && Character.isWhitespace(str.charAt(end - 1)); end--) {
            }
        } else {
            for (; end != 0 && strip.indexOf(str.charAt(end - 1)) != -1; end--) {
            }
        }
        return str.substring(0, end);
    }

    public static String stripStart(String str, String strip) {
        if (str == null) {
            return null;
        }
        int start = 0;
        int sz = str.length();
        if (strip == null) {
            for (; start != sz && Character.isWhitespace(str.charAt(start)); start++) {
            }
        } else {
            for (; start != sz && strip.indexOf(str.charAt(start)) != -1; start++) {
            }
        }
        return str.substring(start);
    }

    public static String upperCase(String str) {
        if (str == null) {
            return null;
        } else {
            return str.toUpperCase();
        }
    }

    public static String lowerCase(String str) {
        if (str == null) {
            return null;
        } else {
            return str.toLowerCase();
        }
    }

    public static String uncapitalise(String str) {
        if (str == null) {
            return null;
        }
        if (str.length() == 0) {
            return "";
        } else {
            return (new StringBuffer(str.length())).append(
                    Character.toLowerCase(str.charAt(0))).append(
                    str.substring(1)).toString();
        }
    }

    public static String capitalise(String str) {
        if (str == null) {
            return null;
        }
        if (str.length() == 0) {
            return "";
        } else {
            return (new StringBuffer(str.length())).append(
                    Character.toTitleCase(str.charAt(0))).append(
                    str.substring(1)).toString();
        }
    }

    public static String swapCase(String str) {
        if (str == null) {
            return null;
        }
        int sz = str.length();
        StringBuffer buffer = new StringBuffer(sz);
        boolean whitespace = false;
        char ch = '\0';
        char tmp = '\0';
        for (int i = 0; i < sz; i++) {
            ch = str.charAt(i);
            if (Character.isUpperCase(ch)) {
                tmp = Character.toLowerCase(ch);
            } else if (Character.isTitleCase(ch)) {
                tmp = Character.toLowerCase(ch);
            } else if (Character.isLowerCase(ch)) {
                if (whitespace) {
                    tmp = Character.toTitleCase(ch);
                } else {
                    tmp = Character.toUpperCase(ch);
                }
            } else {
                tmp = ch;
            }
            buffer.append(tmp);
            whitespace = Character.isWhitespace(ch);
        }

        return buffer.toString();
    }

    public static String capitaliseAllWords(String str) {
        if (str == null) {
            return null;
        }
        int sz = str.length();
        StringBuffer buffer = new StringBuffer(sz);
        boolean space = true;
        for (int i = 0; i < sz; i++) {
            char ch = str.charAt(i);
            if (Character.isWhitespace(ch)) {
                buffer.append(ch);
                space = true;
            } else if (space) {
                buffer.append(Character.toTitleCase(ch));
                space = false;
            } else {
                buffer.append(ch);
            }
        }

        return buffer.toString();
    }

    public static String getNestedString(String str, String tag) {
        return getNestedString(str, tag, tag);
    }

    public static String getNestedString(String str, String open, String close) {
        if (str == null) {
            return null;
        }
        int start = str.indexOf(open);
        if (start != -1) {
            int end = str.indexOf(close, start + open.length());
            if (end != -1) {
                return str.substring(start + open.length(), end);
            }
        }
        return null;
    }

    public static int countMatches(String str, String sub) {
        if (str == null) {
            return 0;
        }
        int count = 0;
        for (int idx = 0; (idx = str.indexOf(sub, idx)) != -1; idx += sub
                .length()) {
            count++;
        }

        return count;
    }

    public static boolean isAlpha(String str) {
        if (str == null) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (!Character.isLetter(str.charAt(i))) {
                return false;
            }
        }

        return true;
    }

    public static boolean isAlphaSpace(String str) {
        if (str == null) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (!Character.isLetter(str.charAt(i)) && str.charAt(i) != ' ') {
                return false;
            }
        }

        return true;
    }

    public static boolean isAlphanumeric(String str) {
        if (str == null) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (!Character.isLetterOrDigit(str.charAt(i))) {
                return false;
            }
        }

        return true;
    }

    public static boolean isAlphanumericSpace(String str) {
        if (str == null) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (!Character.isLetterOrDigit(str.charAt(i))
                    && str.charAt(i) != ' ') {
                return false;
            }
        }

        return true;
    }

    public static boolean isNumeric(String str) {
        if (str == null) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }

        return true;
    }

    public static boolean isNumericSpace(String str) {
        if (str == null) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != ' ') {
                return false;
            }
        }

        return true;
    }

    public static String defaultString(String str) {
        return defaultString(str, "");
    }

    public static String defaultString(String str, String defaultString) {
        return str != null ? str : defaultString;
    }

    public static String reverse(String str) {
        if (str == null) {
            return null;
        } else {
            return (new StringBuffer(str)).reverse().toString();
        }
    }

    public static String reverseDelimitedString(String str, String delimiter) {
        String strs[] = split(str, delimiter);
        reverseArray(strs);
        return join(strs, delimiter);
    }

    private static void reverseArray(Object array[]) {
        int i = 0;
        for (int j = array.length - 1; j > i; i++) {
            Object tmp = array[j];
            array[j] = array[i];
            array[i] = tmp;
            j--;
        }

    }

    public static boolean containsOnly(String str, char valid[]) {
        if (str == null || valid == null) {
            return false;
        }
        int strSize = str.length();
        int validSize = valid.length;
        for (int i = 0; i < strSize; i++) {
            boolean contains = false;
            for (int j = 0; j < validSize; j++) {
                if (valid[j] != str.charAt(i)) {
                    continue;
                }
                contains = true;
                break;
            }

            if (!contains) {
                return false;
            }
        }

        return true;
    }

	/**
	 * 将字符串形式的整型值转换成整数，如："234"-->234
	 * 可以处理象"12,345"的形式
	 *
	 * @param value
	 * @return
	 */
	public static int toInt(String value) {
		return (int) toLong(value);
	}

	/**
	 * 将字符串形式的长整型值转换成长整数，如："234"-->234
	 * 可以处理象"12,345"的形式
	 *
	 * @param value
	 * @return
	 */
	public static long toLong(String value) {
		if (value == null) {
			return 0L;
		}
		String szTemp = "";
		for (int i = 0; i < value.length(); i++) {
			if (value.charAt(i) != ',') {
				szTemp = szTemp + value.charAt(i);
			}
		}
		try {
			double dd = Double.parseDouble(szTemp);
			long l1 = (long) dd;
			return l1;
		} catch (NumberFormatException e) {
			long l = 0L;
			return l;
		}
	}

	/**
	 * 将字符串形式的浮点数值转换成浮点数，如："234.567"-->234.567
	 * 可以处理象"12,345.567"的形式
	 *
	 * @param value
	 * @return
	 */
    public static double toDouble(String value) {
        if (value == null) {
			return 0.0D;
		}
		String szTemp = "";
		for (int i = 0; i < value.length(); i++) {
			if (value.charAt(i) != ',') {
				szTemp = szTemp + value.charAt(i);
			}
		}
		try {
			double d = Double.parseDouble(szTemp);
			return d;
		} catch (NumberFormatException e) {
			double d1 = 0.0D;
			return d1;
		}
    }

	/**
	 * 将字符串日期转换成Date类型 Date d = DateFormat("2001-02-17");
	 *
	 * @param datetime
	 * @return
	 */
	public static java.sql.Date toDate(String datetime) {
		String[] dt = datetime.split("//-");
		if (dt == null || dt.length != 3) {
			return null;
		}
		int[] idt = new int[3];
		for (int i = 0; i < idt.length; i++) {
			idt[i] = toInt(dt[i]);
		}
		java.util.Calendar c = java.util.Calendar.getInstance();
		c.set(idt[0], idt[1] - 1, idt[2]);
		return new java.sql.Date(c.getTime().getTime());
	}

	/**
	 * dd/MM/yyyy -->> yyyy-MM-dd
	 *
	 * @param date
	 * @return
	 */
	public static String conversion(String date) {
		if (date.indexOf("") == -1)
			return "";
		String[] dmy = date.split("\\/");
		if (dmy.length == 3) {
			return dmy[2] + "-" + dmy[1] + "-" + dmy[0];
		} else {
			return "";
		}
	}

	/**
	 * 首字母大写
	 * @param name
	 * @return
	 */
	public static String initialString(String name){
		if(name==null) return "";
		String s = name.trim();
		if(!"".equals(s)){
			String i = s.substring(0,1);
			s = i.toUpperCase()+s.substring(1);
		}
		return s;
	}
}
